<template>
  <div class="echarts-box">
    <div :id="id" class="echart"></div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import { debounce } from "@/utils";
import "echarts-gl";

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  options: {
    type: Object,
    default: {},
  },
  isEchartsGl: {
    type: Boolean,
    default: false,
  },
});

let chartInstance = null;

const initChart = () => {
  if (chartInstance) chartInstance.dispose();
  if (props.isEchartsGl) {
    chartInstance = echarts.init(document.getElementById(props.id), null, {
      renderer: "webgl",
    });
  } else {
    chartInstance = echarts.init(document.getElementById(props.id));
  }
  chartInstance.setOption(props.options);
};

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

const debouncedResize = debounce(handleResize, 500);

onMounted(() => {
  initChart();
  window.addEventListener("resize", debouncedResize);
});

watch(props.options, () => {
  initChart();
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener("resize", debouncedResize);
});
</script>

<style scoped lang='scss'>
.echarts-box,
.echart {
  width: 100%;
  height: 100%;
}
</style>
